<template>
  <el-cascader
    ref="anvilCascader"
    v-model="cascaderValue"
    :disabled="disabled"
    :options="dicData"
    :props="cascaderProps"
    :size="size"
    :clearable="clearable"
    :filterable="filterable"
    :show-all-levels="showAllLevels"
    :separator="separator"
    style="width: 100%"
    @change="handleCascaderChange"
  />
</template>
  
  <script>
import { customApiExecute, modelApiExecute, localApiExecute, getParamsWithMerge } from '../../utils/common-methods';
import { useAnvilCodeStore } from '../../store/modules/code';

export default {
  name: 'AnvilCascader',
  inheritAttrs: false,
  props: {
    modelValue: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    formData: {
      type: Object,
      default: () => {}
    },
    separator: {
      type: String,
      default: ''
    },
    filterable: {
      type: Boolean,
      default: false
    },
    clearable: {
      type: Boolean,
      default: false
    },
    showAllLevels: {
      type: Boolean,
      default: true
    },
    size: {
      type: String,
      default: 'default'
    },
    cascaderProps: {
      type: Object,
      default: () => {}
    },
    dicOption: {
      type: String,
      default: 'remote'
    },
    dicRes: {
      type: String,
      default: ''
    },
    ajaxSetting: {
      type: Object,
      default: () => {}
    },
    staticJson: {
      type: String,
      default: ''
    },
    bindLabel: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      cascaderValue: '',
      localData: {},
      dicData: []
    };
  },
  watch: {
    modelValue: {
      handler(newVal) {
        this.cascaderValue = newVal;
      },
      immediate: true
    },
    cascaderValue: {
      handler(newVal) {
        this.$emit('update:modelValue', newVal);
      }
    },
    formData: {
      handler(newVal) {
        this.localData = newVal;
      },
      immediate: true,
      deep: true
    },
    localData: {
      handler(v) {
        this.$emit('update:formData', v);
      },
      deep: true
    }
  },
  mounted() {
    this.asyncLoad();
  },
  methods: {
    asyncLoad() {
      this.getCascaderData();
    },
    getCascaderData() {
      try {
        if (this.dicOption == 'static') {
          this.dicData = JSON.parse(this.staticJson);
        } else if (this.dicOption == 'remote' && this.ajaxSetting.url) {
          const { type, url, method, contentType, hookBefore, hookAfter, headers, params, noLoading } = this.ajaxSetting;

          const anvilCodeStore = useAnvilCodeStore();
          const { instance } = anvilCodeStore.getPageForm(this.$attrs.pageId);
          const callback = (response) => {
            let res = response;
            if (hookAfter) {
              console.log('调用后置钩子', hookAfter);
              // 获取当前表单实例
              res = instance[hookAfter](response);
            }
            let dicts = [];
            if (this.dicRes) {
              dicts = eval(this.dicRes);
            } else {
              dicts = res;
            }

            console.log('dicts', dicts);
            this.dicData = dicts;
          };

          let Header = {},
            Param = {};

          if (headers) {
            headers.map((item) => {
              Header[item.key] = item.value;
            });
          }

          Param = getParamsWithMerge(this, params);

          if (hookBefore) {
            console.log('调用前置钩子', hookBefore);
            Param = instance[hookBefore](Param);
          }

          const config = {
            url,
            method,
            contentType,
            headers: Header,
            params: Param,
            callback
          };

          switch (type) {
            case 'ajax':
              return customApiExecute(config, { noLoading });
            case 'ajaxModel':
              return modelApiExecute(config, { noLoading });
            case 'ajaxLocal':
              return localApiExecute(config, { noLoading });
          }
        }
      } catch (e) {
        console.log('getCascaderData Error!', e);
      }
    },
    handleCascaderChange() {
      const nodes = this.$refs.anvilCascader.getCheckedNodes();
      let label = '';
      if (nodes && nodes.length) {
        label = nodes.map(node => node.text ?? '').join(',');
        console.log('label', label);
      }
      if (this.bindLabel && this.localData) {
        this.localData[this.bindLabel] = label;
      }
    }
  }
};
</script>